package com.searching.core.dao.Impl;

import com.searching.core.dao.DataSourceFactory;
import com.searching.core.dao.FileIndexDao;
import com.searching.core.model.Condition;
import com.searching.core.model.FileType;
import com.searching.core.model.Thing;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

/**
 * 作用：
 * 1.insert()：插入索引
 * 2.search():在sql中输入查找语句，并返回查找到的索引对象（名称，路径，深度，文件类型）
 */

public class FileIndexDaoImpl implements FileIndexDao {
    private final DataSource dataSource;

    public FileIndexDaoImpl(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public void insert(Thing thing) {

        //java.sql 相关的类
        Connection connection = null;
        //public interface PreparedStatement extends Statement{}
        PreparedStatement statement = null;
        try {
            //1.获取数据库链接
            connection = dataSource.getConnection();
            //2.准备数据库语句
            //insert into fileIndex
            String sql = "insert into file_index(name,path,depth,file_type) values(?,?,?,?)";
            //3.准备命令
            statement = connection.prepareStatement(sql);
            //4.设置参数1,2,3,4
            statement.setString(1, thing.getName());
            statement.setString(2, thing.getPath());
            statement.setInt(3, thing.getDepth());
            //fileTyoe.DOC-->DOC
            statement.setString(4, thing.getFileType().name());
            //5.执行命令
            statement.executeUpdate();
        } catch (SQLException e) {
            //e.printStackTrace();
        } finally {
            releaseResource(null, statement, connection);

        }
    }
    @Override
    public List<Thing> search(Condition condition) {
        //
        List<Thing> things = new ArrayList<>();
        Connection connection = null;
        PreparedStatement statement = null;
        //java.sql-->ResultSet
        ResultSet resultSet = null;
        try{
            //1.获取数据库链接
            connection = dataSource.getConnection();
            //2.准备数据库语句
            //insert into fileIndex
//            String sql = "select name,path,depth,file_type from file_index";
            //name: __like__
            //fileType : =
            //limit ： limit offset
            //orderByAsc ：order by
            //不用Stringbuffer: buffer线程安全，但此处不会出现多线程访问
            StringBuilder sqlBuilder = new StringBuilder();
            sqlBuilder.append(" select name,path,depth,file_type from file_index ");
            sqlBuilder.append(" where ")
                    //name匹配：前模糊，后模糊，前后模糊
                    //名字的模糊匹配输入
                    .append(" name like '%")
                    .append(condition.getName())
                    .append("%' ");
            if((condition.getFileType() != null)){
                sqlBuilder.append(" and file_type = '")
                        .append(condition.getFileType().toUpperCase())
                        .append("'");
            }
            //limit order by 必选


            sqlBuilder.append(" order by depth ")
                    .append(condition.isOrderByAsc() ? "asc " : "desc ");
            if(condition.getLimit() != null) {
                sqlBuilder.append("limit ")
                        .append(condition.getLimit())
                        .append(" offset 0");
            }
                       System.out.println(sqlBuilder.toString());

            //3.准备命令
            statement = connection.prepareStatement(sqlBuilder.toString());
//          statement = connection.prepareStatement(sql);

            //4.设置参数1,2,3,4
//            statement.setString(1,thing.getName());
//            statement.setString(2,thing.getPath());
//            statement.setInt(3,thing.getDepth());
//            statement.setString(4,thing.getFileType().name());
            //5.执行命令
            resultSet = statement.executeQuery();
            //6.处理结果
            while(resultSet.next()){
                //数据库中的行记录-->java对象Thing
                Thing thing = new Thing();
                thing.setName(resultSet.getString("name"));
                thing.setPath(resultSet.getString("path"));
                thing.setDepth(resultSet.getInt("depth"));
                String fileType = resultSet.getString("file_type");
                thing.setFileType(FileType.lookupByName(fileType));
                things.add(thing);

                //resultSet.getString("name");
            }
        }catch(SQLException e) {
           // e.printStackTrace();
        }finally {
            releaseResource(null, statement, connection);
        }
        return things;
    }
    //关闭流__>方法
    private void releaseResource(ResultSet resultSet, PreparedStatement statement, Connection connection) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
}

//    public static void main(String[] args) {
//
//
//        FileIndexDao fileIndexDao = new FileIndexDaoImpl(DataSourceFactory.dataSource());
//
//        DataSourceFactory.initDatabase();
//        Thing thing = new Thing();
//        thing.setName("简历2.ppt");
//        thing.setPath("D:\\a\\b\\简历2.ppt");
//        thing.setDepth(3);
//        thing.setFileType(FileType.DOC);
//
////        fileIndexDao.insert(thing);
//        Condition condition = new Condition();
//        condition.setName("简历");
//        condition.setLimit(2);
//        condition.setFileType("IMG");
//        condition.setOrderByAsc(true);
//
////        List<Thing> things = fileIndexDao.search(new Condition());
//      List<Thing> things = fileIndexDao.search(condition);
//
//        for(Thing t : things) {
//            System.out.println(t);
//        }
//    }


}
